package com.seecen.HJM.controller;

import cn.hutool.captcha.generator.MathGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seecen.HJM.constant.MessageConstant;
import com.seecen.HJM.model.dto.CaptchaCodeDto;
import com.seecen.HJM.model.dto.UserLoginDTO;
import com.seecen.HJM.model.dto.UserRegisterDTO;
import com.seecen.HJM.model.dto.UserResetPasswordDTO;
import com.seecen.HJM.model.entity.User;
import com.seecen.HJM.result.DataVo;
import com.seecen.HJM.service.EmailService;
import com.seecen.HJM.service.FeedbackService;
import com.seecen.HJM.service.IUserService;
import com.seecen.HJM.service.MinioService;
import com.seecen.HJM.util.BindingResultUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/admin/user")
@Slf4j
public class AdminUserController {
    @Autowired
    private IUserService userService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private EmailService emailService;
    @Autowired
    private FeedbackService feedbackService;
    private static final String CAPTCHA_CODE_KEY = CaptchaController.Captcha_Code;
    private static final ThreadLocal<MathGenerator> MATH_GENERATOR = ThreadLocal.withInitial(MathGenerator::new);
    @Autowired
    private MinioService minioService;
    @GetMapping("/{id}")
    public DataVo getById(@PathVariable Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            return DataVo.error("用户不存在");
        }
        // 注意：不修改密码字段（保持加密后的密文，前端不需要展示）
        return DataVo.success(user);
    }
    @GetMapping("/getUserList")
    public DataVo getUserList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String userAvatar,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String userStatus
    ) {
        IPage<User> userIPage = new Page<>(page, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(userAvatar)) {
            queryWrapper.like("user_avatar", userAvatar);
        }
        if (StringUtils.hasText(username)) {
            queryWrapper.like("username", username);
        }
        if (StringUtils.hasText(phone)) {
            queryWrapper.like("phone", phone);
        }
        if (StringUtils.hasText(email)) {
            queryWrapper.like("email", email);
        }
        if (StringUtils.hasText(userStatus)) {
            queryWrapper.like("status", userStatus);
        }
        List<User> userList = userService.list(userIPage, queryWrapper);
        userIPage.setRecords(userList);
        return DataVo.success(userIPage);
    }


    //添加用户
    @PostMapping("/add")
    public DataVo<?> register(@RequestBody User user) {
        boolean success = userService.register(user);
        if (success) {
            return DataVo.success("注册成功");
        } else {
            return DataVo.error("注册失败，用户名已存在");
        }
    }

    /**
     * 发送验证码
     *
     * @param email 邮箱
     * @return 结果
     */
    @GetMapping("/sendVerificationCode")
    public DataVo sendVerificationCode(@RequestParam @Email String email) {
        return userService.sendVerificationCode(email);
    }

    @PatchMapping("/resetUserPassword")
    public DataVo resetUserPassword(@RequestBody @Valid UserResetPasswordDTO userResetPasswordDTO, BindingResult bindingResult) {
        // 校验失败时，返回错误信息
        String errorMessage = BindingResultUtil.handleBindingResultErrors(bindingResult);
        if (errorMessage != null) {
            return DataVo.error(errorMessage);
        }

        // 验证验证码是否正确
        boolean isCodeValid = userService.verifyVerificationCode(userResetPasswordDTO.getEmail(), userResetPasswordDTO.getVerificationCode());
        if (!isCodeValid) {
            return DataVo.error(MessageConstant.VERIFICATION_CODE + MessageConstant.INVALID);
        }

        return userService.resetUserPassword(userResetPasswordDTO);
    }


    @PostMapping("/logoutUser")
    public DataVo logoutUser(@RequestHeader("Authorization") String token) {
        log.info("调用用户登出，原始Token：{}", token); // 打印原始Token，确认格式

        // 关键修复：去除 "Bearer " 前缀（长度为7，包含空格）
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 截取掉前缀，得到纯Token
            log.info("处理后的Token：{}", token);
        } else {
            log.error("Token格式错误，未包含Bearer前缀");
            return DataVo.error("登出失败：Token格式错误");
        }

        return userService.logout(token); // 传递处理后的纯Token给服务层
    }

    //用户注册+邮箱验证
    //数据库好像指定了唯一性
    @PostMapping("/registerUser")
    public DataVo<?> registerUser(@RequestBody @Valid UserRegisterDTO userRegisterDTO) {
        //获取邮箱和验证码
        String email = userRegisterDTO.getEmail();
        String inputCode = userRegisterDTO.getVerificationCode();
        //从Redis获取存储的验证码
        String redisKey = "email:code:" + email;
        String storedCode = redisTemplate.opsForValue().get(redisKey);
        //验证验证码状态
        if (storedCode == null) {
            return DataVo.error(MessageConstant.VERIFICATION_CODE + "已过期，重新验证码");
        }
        if (!storedCode.equals(inputCode)) {
            return DataVo.error(MessageConstant.VERIFICATION_CODE + MessageConstant.FORMAT_ERROR);
        }
        //DTO转换为实体类
        User user = new User();
        BeanUtils.copyProperties(userRegisterDTO, user);
        //设置实体类额外属性
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setUserStatus(0);
        //0表示启用
        String success = userService.registerUser(user);
        if ("success".equals(success)) {
            //注册成功，删除验证码防止重复使用
            redisTemplate.delete(redisKey);
            //注册成功返回注册成功
            return DataVo.success(MessageConstant.REGISTER + MessageConstant.SUCCESS);
        } else {
            //失败返回注册失败，用户名已存在
            return DataVo.error(MessageConstant.REGISTER + MessageConstant.FAILED + "," + success);
        }
    }

    @PostMapping("/login/username")
    public DataVo<String> loginByUsername(
            @Validated(UserLoginDTO.UsernameLoginGroup.class)
            @RequestBody UserLoginDTO loginDTO, HttpSession httpSession) {
        //session获取验证码
        CaptchaCodeDto codeDto = (CaptchaCodeDto) httpSession.getAttribute(CAPTCHA_CODE_KEY);

        if (codeDto == null) {
            log.warn("管理员登录-验证码不存在，用户名：{}", loginDTO.getUsername());
            return DataVo.error("验证码不存在");
        }
        if (LocalDateTime.now().isAfter(codeDto.getExpDate())) {
            httpSession.removeAttribute(CAPTCHA_CODE_KEY);
            log.warn("管理员登录-验证码过期，用户名：{}", loginDTO.getUsername());
            return DataVo.error("验证码过期");
        }

        if (!MATH_GENERATOR.get().verify(codeDto.getCode(), loginDTO.getCode())) {
            log.warn("管理员登录-验证码错误，用户名：{}，用户输入：{}，正确答案：{}",
                    loginDTO.getUsername(), loginDTO.getCode(), codeDto.getCode());
            return DataVo.error("验证码输入错误");
        }
        //验证码验证通过，立即清理（防止重复使用）
        httpSession.removeAttribute(CAPTCHA_CODE_KEY);
        // 调用服务层处理用户名登录逻辑
        return userService.loginByUsername(loginDTO);
    }

    /**
     * 邮箱登录
     */
    @PostMapping("/login/email")
    public DataVo<String> loginByEmail(
            @Validated(UserLoginDTO.EmailLoginGroup.class)
            @RequestBody UserLoginDTO loginDTO) {
        // 调用服务层处理邮箱登录逻辑
        return userService.loginByEmail(loginDTO);
    }
    // 查询用户
//    @GetMapping("/search")
//    public ResponseEntity<List<User>> searchUsers(@RequestParam String keyword) {
//        List<User> users = userService.searchUsers(keyword);
//        return ResponseEntity.ok(users);
//    }

    @GetMapping("/search")
    public DataVo<List<User>> searchUsers(@RequestParam String keyword) {
        List<User> users = userService.searchUsers(keyword);
        return DataVo.success(users);
    }




    @PutMapping("/update")
    public DataVo<?> updateUser(@RequestBody User user) {

        System.out.println("更新用户信息：" + user); // 添加日志
        System.out.println("用户头像：" + user.getUserAvatar()); // 检查头像字段
        boolean success = userService.updateUser(
                user.getUserId(),
                user.getUsername(),
                user.getUserAvatar(),
                user.getPhone(),
                user.getPassword(),
                user.getEmail(),
                user.getUserStatus(),
                user.getUpdateTime(),
                user.getIntroduction()
        );
        return success ? DataVo.success("更新成功") : DataVo.error("更新失败");
    }

    //更新用户头像
    @PatchMapping("/updateUserAvatar/{id}")
    public DataVo updateArtistAvatar(@PathVariable("id") Long userId, @RequestParam("userAvatar") MultipartFile userAvatar) {
        String avatarUrl = minioService.uploadFile(userAvatar, "users");  // 上传到 user 目录
        return userService.updateUserAvatar(userId, avatarUrl);
    }


    @DeleteMapping("/delete")
    public DataVo<?> deleteUser(@RequestParam Long userId) {
        if (userId == null) {
            return DataVo.error("用户id不能为空");
        }
//        feedbackService.removeByUserId(userId);
        boolean success = userService.deleteUser(userId);
        return success ? DataVo.success("删除成功") : DataVo.error("删除失败");
    }


    @GetMapping("/active-users")
    public DataVo<Long> getActiveUsersThisMonth() {
        long count = userService.getActiveUsersThisMonth();
        return DataVo.success(count);
    }

//        @GetMapping("/active-users")
//    public DataVo<Long> getActiveUsersThisMonth(@RequestParam String startDate,
//                                                @RequestParam String endDate) {
//            LocalDateTime start = LocalDateTime.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//            LocalDateTime end = LocalDateTime.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//            long count = userService.getActiveUsersThisMonth(start, end);
//            return DataVo.success(count);
//    }

    // 用户总量
//    @GetMapping("/total-users")
//    public ResponseEntity<Long> getTotalUsers() {
//        long count = userService.getTotalUsers();
//        return ResponseEntity.ok(count);
//    }

    @GetMapping("/total-users")
    public DataVo<Long> getTotalUsers() {
        long count = userService.getTotalUsers();
        return DataVo.success(count);
    }
}
